package nkr1pt.popkorn.events;

import java.io.File;
import nkr1pt.popkorn.download.DownloadCandidate;
import nkr1pt.popkorn.download.DownloadCandidateItem;

/**
 *
 * @author Kristof Vanhaeren
 */
public class PopkornEventFactory {

    public PopkornEvent newEvent(PopkornEvent.EventType type) {
        String source = traceSource(Thread.currentThread().getStackTrace());
        return new PopkornEvent(source, type);
    }

    public DownloadEvent newEvent(PopkornEvent.EventType type, File file) {
        DownloadEvent event = new DownloadEvent(newEvent(type));
        event.setFile(file);
        return event;
    }

    public DownloadEvent newEvent(PopkornEvent.EventType type, DownloadCandidate candidate) {
        DownloadEvent event = new DownloadEvent(newEvent(type));
        event.setDownloadCandidate(candidate);
        return event;
    }

    public DownloadEvent newEvent(PopkornEvent.EventType type, DownloadCandidateItem item) {
        DownloadEvent event = new DownloadEvent(newEvent(type));
        event.setDownloadCandidateItem(item);
        return event;
    }

    private String traceSource(StackTraceElement[] e) {
        int index = 0;
        for (int i=e.length-1; i>=0; i--) {
            StackTraceElement s = e[i];
            if (s.getClassName().equals(getClass().getName()) && s.getMethodName().equals("newEvent")) {
                index = i;
                break;
            }
        }

        StackTraceElement s = e[++index];
        String clazz = s.getClassName();
        String method = s.getMethodName();
        return clazz+"."+method;
    }
}